'''
Author: duliang thinktanker@163.com
Date: 2024-03-02 16:13:14
LastEditors: duliang thinktanker@163.com
LastEditTime: 2024-03-02 21:31:15
FilePath: \opencv2\cutimage.py
Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
'''
import cv2
import numpy as np
# import ctypes

# # 获取当前控制台窗口句柄
# hWnd = ctypes.windll.kernel32.GetConsoleWindow()

# 加载或初始化一张图片
img = cv2.imread('./2z.png')  # 替换为你要处理的图片路径
if img is None:
    img = np.zeros((500, 500, 3), np.uint8)  # 或者使用空白图像作为默认

# 初始化矩形框起始点和是否正在绘制标志
rect_start = None
is_drawing = False
rect = []


def draw_rectangle(event, x, y, flags, param):
    global rect_start, is_drawing, rect, img

    if event == cv2.EVENT_LBUTTONDOWN:
        rect_start = (x, y)  # 记录矩形开始点
        is_drawing = True

    elif event == cv2.EVENT_MOUSEMOVE and is_drawing:
        rect_end = (x, y)
        img = cv2.imread('./2z.png')
        cv2.rectangle(img, rect_start, rect_end, (0, 255, 0), 2)
        cv2.imshow('Image', img)  # 实时更新显示窗口

    elif event == cv2.EVENT_LBUTTONUP:
        rect_end = (x, y)
        # img = cv2.imread('./2z.png')
        cv2.rectangle(img, rect_start, rect_end, (0, 255, 0), 2)
        rect.append([
            min(rect_start[0], rect_end[0]),
            min(rect_start[1], rect_end[1]),
            max(rect_start[0], rect_end[0]),
            max(rect_start[1], rect_end[1])
        ])
        is_drawing = False


# 创建一个窗口并设置鼠标回调函数
cv2.namedWindow('Image')
cv2.setMouseCallback('Image', draw_rectangle)

while True:
    cv2.imshow('Image', img)

    # 检查按键事件
    key = cv2.waitKey(1) & 0xFF
    # 保存
    if rect and key == ord('s'):
        print(f" {rect[-1]}")
        n = input("名称：")
        print(n)
        continue
    # 当用户按下 'r' 键时清空已画的矩形并重新开始
    if key == ord('r'):
        img = cv2.imread('./2z.png')  # 重新加载原图（可选）
        rect.clear()
        cv2.imshow('Image', img)
    # 按 'q' 键退出
    elif key == ord('q'):
        break

# 记录最后一次选择的矩形范围

cv2.destroyAllWindows()

# 现在你可以访问 `rect` 列表，它包含了每次框选操作后矩形的左上角(x, y)与右下角(x, y)坐标

